import {createStore} from 'vuex';
import createPersistedState from 'vuex-persistedstate';

//创建一个store实例
const store = createStore({
    state: {
        isFresh: true,//是否刷新页面
        userInfo: {},//用户信息
        isLogin: false,//是否登录
        connectStatus: false,//socket连接状态
        inChess: false,//是否正在比赛
        chessTime: '',//比赛计时时间
    },
    getters: {
        getIsFresh(state) {
            return state.isFresh;
        },
        getIsLogin(state) {
            return state.isLogin;
        },
        getUserInfo(state) {
            return state.userInfo;
        },
        getConnectStatus(state) {
            return state.connectStatus;
        },
        getInChess(state) {
            return state.inChess;
        },
        getChessTime(state) {
            return state.chessTime;
        }
    },
    mutations: {
        setIsFresh(state, isFresh) {
            state.isFresh = isFresh;
        },
        setIsLogin(state, isLogin) {
            state.isLogin = isLogin;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },
        changeConnectStatus(state, status) {
            state.connectStatus = status;
        },
        setInChess(state, inChess) {
            state.inChess = inChess;
        },
        setChessTime(state, chessTime) {
            state.chessTime = chessTime;
        }
    },
    actions: {
        handleSetIsFresh(context, isFresh) {
            context.commit('setIsFresh', isFresh);
        },
        handleSetIsLogin(context, isLogin) {
            context.commit('setIsLogin', isLogin);
        },
        handleSetUserInfo(context, userInfo) {
            context.commit('setUserInfo', userInfo);
        },
        handleChangeConnectStatus(context, status) {
            context.commit('changeConnectStatus', status);
        },
        handleSetInChess(context, inChess) {
            context.commit('setInChess', inChess);
        },
        handleSetChessTime(context, chessTime) {
            context.commit('setChessTime', chessTime);
        }
    },
    plugins: [createPersistedState({//持久化
        key: 'cbl-vuex-key',
        storage: window.localStorage,
        reducer(val) {
            return {
                userInfo: val.userInfo,
                isLogin: val.isLogin,
                chessTime: val.chessTime
            }
        }
    })]
});

export default store;